package com.edgardeng.education.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.edgardeng.education.entity.JsonResponse;
import com.edgardeng.education.entity.School;
import com.edgardeng.education.entity.SchoolClass;
import com.edgardeng.education.service.ISchoolClassService;
import com.edgardeng.education.service.ISchoolService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 学校 前端控制器
 * </p>
 *
 * @author edgardeng
 * @since 2020-04-28
 */
@RestController
@RequestMapping("/api/school")
public class SchoolController extends BaseController {

    @Autowired
    ISchoolService baseService;

    @Autowired
    ISchoolClassService classService;


    @GetMapping()
    public IPage<School> schoolPage(
            @RequestParam(value = "size", required = false, defaultValue = "10") Integer size,
            @RequestParam(value = "current", required = false, defaultValue = "1") Integer current,
            School entity) {
        Page<School> page = new Page<>(current, size); // current page and page size
        LambdaQueryWrapper<School> queryWrapper = new LambdaQueryWrapper<>();
        if(entity != null){
            if(!StringUtils.isEmpty(entity.getProvince())){
                queryWrapper.like(School::getProvince, entity.getProvince());
            }
        }
        IPage<School> schoolPage = baseService.page(page, queryWrapper);
        return schoolPage;
    }

    @PostMapping
    public JsonResponse addSchool(@RequestBody School entity) {
        boolean r = baseService.save(entity);
        return JsonResponse.result(r);
    }

    @GetMapping("/{id}")
    public School getSchool(@PathVariable Long id) {
        School r = this.baseService.getById(id);
        return r;
    }

    /**
     * 某个学校的班级
     * @param id
     * @return
     */
    @GetMapping("/{id}/class")
    public List<SchoolClass> listSchoolClass(@PathVariable Long id) {
        LambdaQueryWrapper<SchoolClass> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SchoolClass::getSchoolId, id);
        return classService.list(queryWrapper);
    }

    @DeleteMapping("/{id}")
    public JsonResponse deleteSchool(@PathVariable Long id) {
        boolean r = this.baseService.removeById(id);
        return JsonResponse.result(r);
    }

    @PutMapping()
    public JsonResponse updateSchool(@RequestBody School entity) {
        boolean r = this.baseService.updateById(entity);
        return JsonResponse.result(r);
    }

}
